package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.module.admin.entity.SysSchool;
import com.mars.module.admin.entity.SysStayApplication;
import com.mars.module.admin.mapper.SysSchoolMapper;
import com.mars.module.admin.service.ISysDictDataService;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysVisaApplicationRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysVisaApplicationMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysVisaApplication;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysVisaApplicationService;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 签证申请业务层处理
 *
 * @author mars
 * @date 2024-03-14
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysVisaApplicationServiceImpl implements ISysVisaApplicationService {

    private final SysVisaApplicationMapper baseMapper;
    private final SysUserMapper userMapper;
    private final ISysDictDataService dataService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysVisaApplication add(SysVisaApplicationRequest request) {
        SysVisaApplication entity = SysVisaApplication.builder().build();
        BeanUtils.copyProperties(request, entity);
        entity.setStatus("0");
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysVisaApplicationRequest request) {
        SysVisaApplication entity = SysVisaApplication.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysVisaApplication getById(Long id) {
        SysVisaApplication e = baseMapper.selectById(id);
        SysUser sysUser = userMapper.selectById(e.getUserId());
        e.setUserName(sysUser == null ? "" : sysUser.getUserName());
        e.setStatusName(dataService.getDictDataById("approve_status", e.getStatus()));
        e.setStayTypeName(dataService.getDictDataById("stay_type", e.getStayType()));
        return e;
    }

    @Override
    public PageInfo<SysVisaApplication> pageList(SysVisaApplicationRequest request) {
        Page<SysVisaApplication> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysVisaApplication> query = this.buildWrapper(request);
        IPage<SysVisaApplication> pageRecord = baseMapper.selectPage(page, query);
        List<SysVisaApplication> records = pageRecord.getRecords();
        List<SysVisaApplication> recordsNew = new ArrayList<>();
        for (SysVisaApplication e : records) {
            SysUser sysUser = userMapper.selectById(e.getUserId());
            e.setUserName(sysUser == null ? "" : sysUser.getUserName());
            e.setStatusName(dataService.getDictDataById("approve_status", e.getStatus()));
            e.setStayTypeName(dataService.getDictDataById("stay_type", e.getStayType()));
            recordsNew.add(e);
        }
        if (StringUtils.isNotBlank(request.getCountry())) {
            recordsNew = recordsNew.stream().filter(e -> e.getCountry().contains(request.getCountry())).collect(Collectors.toList());
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysVisaApplication> list(SysVisaApplicationRequest request) {
        LambdaQueryWrapper<SysVisaApplication> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    @Override
    public Map<String, Long> visaApplyCount() {
        List<SysVisaApplication> visaList = baseMapper.selectList(new QueryWrapper<>());
        visaList.stream().forEach(
                e -> {
                    e.setCreateTimeDate(e.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM")));
                }
        );
        Map<String, Long> collect = visaList.stream().collect(Collectors.groupingBy(SysVisaApplication::getCreateTimeDate,
                Collectors.counting()));
        Map<String, Integer> sortedMap = new LinkedHashMap<>();
        sortedMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));
        sortedMap.forEach((k, v) -> System.out.println(k + ": " + v));
        return collect;
    }

    private LambdaQueryWrapper<SysVisaApplication> buildWrapper(SysVisaApplicationRequest param) {
        LambdaQueryWrapper<SysVisaApplication> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getStayType())) {
            query.like(SysVisaApplication::getStayType, param.getStayType());
        }
        if (StringUtils.isNotBlank(param.getPassportNo())) {
            query.like(SysVisaApplication::getPassportNo, param.getPassportNo());
        }
        if (StringUtils.isNotBlank(param.getTelephone())) {
            query.like(SysVisaApplication::getTelephone, param.getTelephone());
        }
        if (StringUtils.isNotBlank(param.getCountry())) {
            query.like(SysVisaApplication::getCountry, param.getCountry());
        }
        if (StringUtils.isNotBlank(param.getReason())) {
            query.like(SysVisaApplication::getReason, param.getReason());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            query.like(SysVisaApplication::getStatus, param.getStatus());
        }
        if (param.getUserId() != null) {
            query.eq(SysVisaApplication::getUserId, param.getUserId());
        }
        return query;
    }

}
